package com.opticon.vaadinR.core;

import org.apache.log4j.Logger;

import java.util.Properties;
import java.util.Set;

/**
 * This class can filter/replace an RSource object.
 */
public class RFilter {
    private static Logger logger = Logger.getLogger(RFilter.class);


    private boolean replaceBackslash = true;

    /**
     * The Filter will lookup Keys, and replace these with their Values.
     */
    private Properties iProperties;

    /**
     * The keys must be surrounded by this token to be replaced by their values.
     */
    public static final String token = "@@@";

    /**
     * Construct a new RFilter instance.
     *
     * @param aProperties Properties instance with Key/Values for Old/New parameters in the RSource file.
     *                    <p/>
     *                    Key: <b>FILENAME</b>, then the filter will match @@@FILENAME@@@
     *                    Value: <b>test.pdf</b> this will be the new value for key matches
     */
    public RFilter(Properties aProperties) {
        iProperties = aProperties;
        //
        if (iProperties == null) {
            iProperties = new Properties();
        }
    }

    /**
     * Construct a new RFilter instance.
     * <p/>
     * Key: <b>FILENAME</b>, then the filter will match @@@FILENAME@@@
     * Value: <b>test.pdf</b> this will be the new value for key matches
     */
    public RFilter() {
        iProperties = new Properties();
    }

    /**
     * Filters the specified String with the preset Key/Values
     * Key/Values are Case sensitive!!
     *
     * @param line String with or without keys.
     * @return new String, all keys are replaced by values.
     */
    public String filter(String line) {
        if (line.indexOf(token) > 0) {
            // Ok, there is something to change in this line!
            String lRunningValue = "";
            String lRunningKey = "";
            Set lKeys = iProperties.keySet();
            for (Object lKey : lKeys) {
                lRunningKey = lKey.toString();
                lRunningValue = iProperties.getProperty(lRunningKey);
                String lReplaceValue = token + lRunningKey + token;

                line = line.replace(lReplaceValue, lRunningValue);
            }
            line = line.replace("\\", "\\\\");
        }


        return line;
    }

    /**
     * Add a new Key/Value pair to be filtered.
     *
     * @param aKey   : <b>FILENAME</b>, then the filter will match token + FILENAME + token
     * @param aValue : <b>test.pdf</b> this will be the new value for key matches
     */
    public void add(String aKey, String aValue) {
        iProperties.put(aKey, aValue);
    }

    /**
     * Returns the Value for the given key. Null if not present.
     *
     * @param aKey
     */
    public String get(String aKey) {
        return iProperties.get(aKey).toString();
    }


    public void setReplaceBackslash(boolean replaceBackslash) {
        this.replaceBackslash = replaceBackslash;
    }
}
